<template>
	<div>
		<CustomDialog
			:title="state.dialog.title"
			v-model:visible="state.dialog.isShowDialog"
			dialogWidth="900px"
			@close="handleCatalogDataClose"
			:dialogFooterBtn="true"
		>
			<!-- <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px"> -->
			<div>
				<el-form ref="catalogDialogFormRef" :model="state.ruleForm" size="default" label-width="90px">
					<el-row>
						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="分类类型" prop="catalogType" :rules="[{ required: true, message: '分类类型不能为空', trigger: 'blue' }]">
								<el-radio-group v-model="state.ruleForm.catalogType" @change="changeCatalogType" :disabled="state.ruleForm.id != ''">
									<el-radio :label="1">一级分类</el-radio>
									<el-radio :label="2">二级分类</el-radio>
									<el-radio :label="3">三级分类</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="分类样式" prop="style" :rules="[{ required: true, message: '分类样式不能为空', trigger: 'blue' }]">
								<div class="sd-flex">
									<div class="category-style" v-if="state.ruleForm.catalogType == 1">
										<div class="category-image" @click="state.ruleForm.style = 'first_one'">
											<img :src="STATIC_URL + FIRST_ONE" class="type-img" :class="{ activeBorder: state.ruleForm.style == 'first_one' }" />
										</div>
										<div class="sd-flex sd-row-center">
											<div class="category-title">样式一</div>
											<el-tooltip placement="right" effect="light">
												<img class="category-icon" :src="STATIC_URL + WARNING" />
												<template #content>
													<el-image style="width: 300px; height: 400px" :src="STATIC_URL + FIRST_ONE" fit="cover" />
												</template>
											</el-tooltip>
										</div>
									</div>
									<div class="category-style" v-if="state.ruleForm.catalogType == 1">
										<div class="category-image" @click="state.ruleForm.style = 'first_two'">
											<img :src="STATIC_URL + FIRST_TWO" class="type-img" :class="{ activeBorder: state.ruleForm.style == 'first_two' }" />
										</div>
										<div class="sd-flex sd-row-center">
											<div class="category-title">样式二</div>
											<el-tooltip placement="right" effect="light">
												<img class="category-icon" :src="STATIC_URL + WARNING" />
												<template #content>
													<el-image style="width: 300px; height: 400px" :src="STATIC_URL + FIRST_TWO" fit="cover" />
												</template>
											</el-tooltip>
										</div>
									</div>

									<div class="category-style" v-if="state.ruleForm.catalogType == 2">
										<div class="category-image" @click="state.ruleForm.style = 'second_one'">
											<img :src="STATIC_URL + SECOND_ONE" class="type-img" :class="{ activeBorder: state.ruleForm.style == 'second_one' }" />
										</div>
										<div class="sd-flex sd-row-center">
											<div class="category-title">样式一</div>
											<el-tooltip placement="right" effect="light">
												<img class="category-icon" :src="STATIC_URL + WARNING" />
												<template #content>
													<el-image style="width: 300px; height: 400px" :src="STATIC_URL + SECOND_ONE" fit="cover" />
												</template>
											</el-tooltip>
										</div>
									</div>

									<div class="category-style" v-if="state.ruleForm.catalogType == 3">
										<div class="category-image" @click="state.ruleForm.style = 'third_one'">
											<img :src="STATIC_URL + THIRD_ONE" class="type-img" :class="{ activeBorder: state.ruleForm.style == 'third_one' }" />
										</div>
										<div class="sd-flex sd-row-center">
											<div class="category-title">样式一</div>
											<el-tooltip placement="right" effect="light">
												<img class="category-icon" :src="STATIC_URL + WARNING" />
												<template #content>
													<el-image style="width: 300px; height: 400px" :src="STATIC_URL + THIRD_ONE" fit="cover" />
												</template>
											</el-tooltip>
										</div>
									</div>
								</div>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="分类名称" prop="catalogName" :rules="[{ required: true, message: '分类名称不能为空', trigger: 'blue' }]">
								<el-input v-model="state.ruleForm.catalogName" placeholder="请输入分类名称" clearable></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="分类权重" prop="sortOrder" :rules="[{ required: true, message: '分类权限不能为空', trigger: 'blue' }]">
								<el-input v-model.number="state.ruleForm.sortOrder" placeholder="请输入分类权重" clearable type="number"></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<el-form-item label="分类描述" prop="description">
								<el-input v-model="state.ruleForm.description" type="textarea" placeholder="请输入分类描述" maxlength="150"></el-input>
							</el-form-item>
						</el-col>

						<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
							<div class="spec-flex">
								<div>分类数据</div>
								<div>
									<el-button text link type="primary" :icon="Plus" @click="addTopNode"> 插入一级分类</el-button>
								</div>
							</div>
							<div style="overflow: auto">
								<div data-v-a5a478b5="" class="custom-tree-header flex">
									<div data-v-a5a478b5="" class="custom-tree-box flex">
										<div class="expanded-width-input">分类名称</div>
										<div class="expanded-width-image flex sa-row-center">分类图片</div>
										<div class="expanded-width-des">描述</div>
										<div class="expanded-width-sort">
											<span class="el-only-child__content el-tooltip__trigger el-tooltip__trigger"> 排序 </span>
										</div>
										<div class="expanded-width-operation">操作</div>
									</div>
								</div>
								<div class="flex d-flex-center">
									<el-tree
										:data="state.ruleForm.catalogs"
										node-key="id"
										default-expand-all
										:expand-on-click-node="false"
										icon="my-class"
										indent="0"
										ref="catalogTreeRef"
									>
										<template #default="{ node, data }">
											<div class="flex drag-item">
												<div class="flex expanded-width-input">
													<div class="expanded-icon flex" v-if="!node.isLeaf" @click="node.expanded = !node.expanded" :class="'level-' + node.level">
														<Plus class="expanded-icon" v-if="!node.expanded"></Plus>
														<Minus v-else class="expanded-icon"></Minus>
													</div>
													<div class="expanded-icon flex" :class="'level-' + node.level" v-else></div>
													<div style="margin-left: 16px">
														<el-input placeholder="请输入分类名称" v-model="data.catalogName" />
													</div>
													<div class="ml12 append-title" v-if="!node.isLeaf">
														<el-button text link type="primary" :icon="Plus" @click="addChildren(node, data)">
															插入{{ node.level == 1 ? '二' : '三' }}级分类</el-button
														>
														<!--														<a class="cursor" @click="addChildren(node, data)">+插入{{ node.level == 1 ? '二' : '三' }}级分类 </a>-->
													</div>
												</div>
												<div class="flex expanded-width-image">
													<el-tooltip class="box-item" effect="dark" content="建议尺寸：缩略图150X150" placement="bottom">
														<div class="goods-image choice-image choice-image-delete" @click="choiceGoodsCatalogImage(data, 2)">
															<el-image v-if="data.picUrl != ''" :src="STATIC_URL + data.picUrl" fit="contain" />
															<el-icon v-else>
																<ele-Plus />
															</el-icon>
															<div class="delete-content" @click.stop="data.picUrl = ''" v-if="data.picUrl != ''">
																<SvgIcon name="ele-DeleteFilled"></SvgIcon>
															</div>
														</div>
													</el-tooltip>
												</div>
												<div class="expanded-width-des">
													<el-input placeholder="请输入分类描述" v-model="data.description" />
												</div>
												<div class="expanded-width-sort">
													<el-input type="number" v-model="data.sortOrder" />
												</div>
												<div class="expanded-width-operation">
													<span>
														<el-switch
															:active-value="1"
															:inactive-value="0"
															v-model="data.hide"
															inline-prompt
															active-text="隐藏"
															inactive-text="正常"
															style="--el-switch-off-color: #13ce66; --el-switch-on-color: #ff4949"
														/>
														<!--														<span style="color: rgb(153, 153, 153)" @click="hideNode(node, data)">隐藏</span> --> </span
													><span style="color: rgb(255, 77, 79); margin-left: 16px" @click="deleteNode(node, data)">删除</span>
												</div>
											</div>
										</template>
									</el-tree>
								</div>
							</div>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="handleCatalogDataClose" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(catalogDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</div>
			</template>
			<!-- </el-dialog> -->
		</CustomDialog>
		<FileChoice ref="FileChoiceRef" @choiceFile="choiceFile"></FileChoice>
	</div>
</template>

<script setup lang="ts" name="goodsCatalogDialog">
import { onMounted, reactive, ref, defineAsyncComponent, nextTick } from 'vue';
import { goodCatalogApi } from '/@/api/goods/catalog/index';
import msg from '/@/utils/messageUtils';
import type { FormInstance, FormRules } from 'element-plus';
import { Plus, Minus } from '@element-plus/icons-vue';
import commonFunction from '/@/utils/commonFunction';
import { STATIC_URL } from '/@/utils/config';
const { randomInt } = commonFunction();
const FileChoice = defineAsyncComponent(() => import('/@/views/file/choice/index.vue'));
const FileChoiceRef = ref();
const catalogDialogFormRef = ref();
const emit = defineEmits(['refresh']);
const catalogTreeRef = ref();

const FIRST_ONE = 'static/images/shop/category/first_one.png';
const FIRST_TWO = 'static/images/shop/category/first_two.png';
const SECOND_ONE = 'static/images/shop/category/second_one.png';
const THIRD_ONE = 'static/images/shop/category/third_one.png';
const WARNING = 'static/images/shop/category/warning.png';
const state = reactive({
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	catalogData: [],
	ruleForm: {
		catalogType: 1,
		showPicUrl: '',
		showIconUrl: '',
		catalogName: '',
		id: '',
		parentId: 0,
		sortOrder: 0,
		description: '',
		picUrl: '',
		iconUrl: '',
		picFileId: '',
		iconFileId: '',
		style: 'first_one',
		catalogs: [] as any,
	},
	// treeCatalogData: [] as any,
	catelogImageType: 0,
});

const tempChoiceGoodsCatalogImage = ref();

const rules = reactive<FormRules>({
	catalogName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
	parentId: [{ required: true, message: '父分类不能为空', trigger: 'blur' }],
	sortOrder: [
		{ required: true, message: '分类排序不能为空', trigger: 'blur' },
		{ type: 'number', message: '排序字段必须数字' },
	],
	picUrl: [{ required: true, message: '分类图片不能为空', trigger: 'blur' }],
	iconUrl: [{ required: true, message: '分类图标不能为空', trigger: 'blur' }],
});

const initCatalog = () => {
	console.log('randInt:', randomInt());

	if (state.ruleForm.catalogType === 1) {
		state.ruleForm.catalogs = [
			{
				id: randomInt(),
				catalogName: '',
				picUrl: '',
				picFileId: '',
				description: '',
				sortOrder: 0,
				hide: 0,
			},
		];
	} else if (state.ruleForm.catalogType === 2) {
		state.ruleForm.catalogs = [
			{
				id: randomInt(),
				catalogName: '',
				picUrl: '',
				picFileId: '',
				description: '',
				sortOrder: 0,
				hide: 0,
				children: [
					{
						id: randomInt(),
						catalogName: '',
						picUrl: '',
						picFileId: '',
						description: '',
						sortOrder: 0,
						hide: 0,
					},
				],
			},
		];
	} else {
		state.ruleForm.catalogs = [
			{
				id: randomInt(),
				catalogName: '',
				picUrl: '',
				picFileId: '',
				description: '',
				sortOrder: 0,
				hide: 0,
				children: [
					{
						id: randomInt(),
						catalogName: '',
						picUrl: '',
						picFileId: '',
						description: '',
						sortOrder: 0,
						hide: 0,
						children: [
							{
								id: randomInt(),
								catalogName: '',
								picUrl: '',
								picFileId: '',
								description: '',
								sortOrder: 0,
								hide: 0,
							},
						],
					},
				],
			},
		];
	}
};

const changeCatalogType = () => {
	console.log('catalog type change : ', state.ruleForm.catalogType);
	state.ruleForm.catalogs = [];
	initCatalog();

	if (state.ruleForm.catalogType == 1) {
		state.ruleForm.style = 'first_one';
	}
	if (state.ruleForm.catalogType == 2) {
		state.ruleForm.style = 'second_one';
	}
	if (state.ruleForm.catalogType == 3) {
		state.ruleForm.style = 'third_one';
	}
};

const addTopNode = () => {
	let topId = state.ruleForm.catalogs[state.ruleForm.catalogs.length - 1].id;
	console.log('topId: ', topId);
	if (state.ruleForm.catalogType == 1) {
		catalogTreeRef.value.insertAfter(
			{
				id: randomInt(),
				catalogName: '',
				picUrl: '',
				picFileId: '',
				description: '',
				sortOrder: 0,
				hide: 0,
			},
			topId
		);
	} else if (state.ruleForm.catalogType == 2) {
		catalogTreeRef.value.insertAfter(
			{
				id: randomInt(),
				catalogName: '',
				picUrl: '',
				picFileId: '',
				description: '',
				sortOrder: 0,
				hide: 0,
				children: [
					{
						id: randomInt(),
						catalogName: '',
						picUrl: '',
						picFileId: '',
						description: '',
						sortOrder: 0,
						hide: 0,
					},
				],
			},
			topId
		);
	} else {
		catalogTreeRef.value.insertAfter(
			{
				id: randomInt(),
				catalogName: '',
				picUrl: '',
				picFileId: '',
				description: '',
				sortOrder: 0,
				hide: 0,
				children: [
					{
						id: randomInt(),
						catalogName: '',
						picUrl: '',
						picFileId: '',
						description: '',
						sortOrder: 0,
						hide: 0,
						children: [
							{
								id: randomInt(),
								catalogName: '',
								picUrl: '',
								picFileId: '',
								description: '',
								sortOrder: 0,
								hide: 0,
							},
						],
					},
				],
			},
			topId
		);
	}
};

const hideNode = (node: any, data: any) => {};

const deleteNode = (node: any, data: any) => {
	const parent = node.parent;
	const children = parent.data.children || parent.data;
	const index = children.findIndex((d: any) => d.id === data.id);
	children.splice(index, 1);
};

const addChildren = (node: any, data: any) => {
	console.log('level: ', node.level);
	// 这里需要修改，，，，，
	if (node.level == 1) {
		if (state.ruleForm.catalogType == 2) {
			data.children.push({
				id: randomInt(),
				catalogName: '',
				picUrl: '',
				picFileId: '',
				description: '',
				sortOrder: 0,
				hide: 0,
			});
		} else {
			data.children.push({
				id: randomInt(),
				catalogName: '',
				picUrl: '',
				picFileId: '',
				description: '',
				sortOrder: 0,
				hide: 0,
				children: [
					{
						id: randomInt(),
						catalogName: '',
						picUrl: '',
						picFileId: '',
						description: '',
						sortOrder: 0,
						hide: 0,
					},
				],
			});
		}
	} else if (node.level == 2) {
		data.children.push({
			id: randomInt(),
			catalogName: '',
			picUrl: '',
			picFileId: '',
			description: '',
			sortOrder: 0,
			hide: 0,
		});
	}
};

const onOpenDialog = (type: string, id: string) => {
	state.dialog.isShowDialog = true;
	state.dialog.type = type;
	console.log('open dialog');
	if (type === 'add') {
		state.dialog.submitTxt = '新增';
		nextTick(() => {
			catalogDialogFormRef.value.resetFields();
			catalogDialogFormRef.value.clearValidate();
			state.dialog.title = '新增商品分类';
			state.ruleForm.showIconUrl = '';
			state.ruleForm.showPicUrl = '';
		});
		initCatalog();
	} else {
		nextTick(() => {
			catalogDialogFormRef.value.resetFields();
			catalogDialogFormRef.value.clearValidate();
		});
		onLoadGoodsCatalogDetail(id);
		state.dialog.submitTxt = '修改';
	}
};

const onLoadGoodsCatalogDetail = async (id: string) => {
	try {
		const { data } = await goodCatalogApi().view(id);
		state.ruleForm.catalogName = data.catalogName;
		state.ruleForm.description = data.description;
		// state.ruleForm.iconUrl = data.iconUrl;
		// state.ruleForm.picUrl = data.picUrl;
		// state.ruleForm.showIconUrl = data.showIconUrl;
		// state.ruleForm.showPicUrl = data.showPicUrl;
		// state.ruleForm.iconFileId = data.iconFileId;
		// state.ruleForm.picFileId = data.picFileId;
		state.ruleForm.sortOrder = data.sortOrder;
		// state.ruleForm.parentId = data.parentId;
		state.ruleForm.catalogType = data.catalogType;
		state.ruleForm.catalogs = data.children;
		state.ruleForm.style = data.style;
		state.ruleForm.id = id;
		console.log('data: ', data);
	} catch (error) {
		msg().error('获取分类详情失败');
	}
};

const onLoadCatalogData = async () => {
	try {
		const { data } = await goodCatalogApi().tree_choice();
		console.log('data: ', data);
		state.catalogData = data;
	} catch (error) {
		msg().error('获取分类父分类失败');
	}
};

const handleCatalogDataClose = () => {
	state.dialog.isShowDialog = false;
};
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	if ('object' == typeof state.ruleForm.parentId) {
		state.ruleForm.parentId = state.ruleForm.parentId[0];
	}

	await formEl.validate(async (valid) => {
		if (valid) {
			try {
				if (state.dialog.type === 'add') {
					await goodCatalogApi().create(state.ruleForm);
				} else {
					await goodCatalogApi().update(state.ruleForm);
				}
				msg().success('success');
				closeDialog(); // 关闭弹窗
				emit('refresh');
			} catch (error: any) {
				msg().error('操作失败，请重试');
			}
		}
	});
};

const choiceGoodsCatalogImage = (data: any, type: number) => {
	tempChoiceGoodsCatalogImage.value = data;
	state.catelogImageType = type;
	FileChoiceRef.value.openFileChoiceDialog();
};

const choiceFileImage = (type: number) => {
	state.catelogImageType = type;

	/**
	 * type = 0 表示分类图标
	 * type = 1 表示分类图片
	 * type = 2 商品分类
	 *
	 */

	FileChoiceRef.value.openFileChoiceDialog();
};

const choiceFile = (choiceFileInfo: ChoiceFileInfo[]) => {
	/**
	 * type = 0 表示分类图标
	 * type = 1 表示分类图片
	 * type = 2 商品分类
	 */

	console.log('choiceFileInfo: ', JSON.stringify(choiceFileInfo));
	if (state.catelogImageType === 0) {
		state.ruleForm.showIconUrl = choiceFileInfo[0].visitAbsPath;
		state.ruleForm.iconUrl = choiceFileInfo[0].visitRelativePath;
		state.ruleForm.iconFileId = choiceFileInfo[0].id;
	} else if (state.catelogImageType === 1) {
		state.ruleForm.showPicUrl = choiceFileInfo[0].visitAbsPath;
		state.ruleForm.picUrl = choiceFileInfo[0].visitRelativePath;
		state.ruleForm.picFileId = choiceFileInfo[0].id;
	} else {
		tempChoiceGoodsCatalogImage.value.picUrl = choiceFileInfo[0].visitRelativePath;
		tempChoiceGoodsCatalogImage.value.picFileId = choiceFileInfo[0].id;
	}
};

const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

defineExpose({
	onOpenDialog,
});
</script>

<style scoped lang="scss">
.goods-image {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 50px;
	width: 50px;
	cursor: pointer;
	border: 1px dashed var(--el-border-color-darker);
	&:hover {
		border: 1px dashed var(--el-color-primary);
	}
}

.drag-item {
	width: 100%;
	height: 58px;
	align-items: center;
}

.expanded-width-id {
	width: 40px;
	padding-left: 16px;
}

.expanded-width-input {
	width: 400px;
	padding-left: 16px;
	align-items: center;
}

.expanded-width-image {
	width: 80px;
}

.append-title a {
	color: var(--el-color-primary);
}

.icon-image {
	box-sizing: border-box;
	margin: 10px;
}

.expanded-width-des {
	width: 260px;
	padding-left: 16px;
}

.expanded-width-sort {
	width: 140px;
	padding-left: 16px;
}

.expanded-width-operation {
	width: 124px;
	padding-left: 16px;
}

.expanded-width-id,
.expanded-width-input,
.expanded-width-image,
.expanded-width-des,
.expanded-width-sort,
.expanded-width-operation {
	flex-shrink: 0;
}

.level-2 {
	padding-left: 20px;
}

.level-3 {
	padding-left: 50px;
}

:deep(.el-tree-node__content) {
	height: 100%;
	width: 100%;
}

.expanded-icon {
	height: 14px;
}

.spec-flex {
	box-sizing: border-box;
	display: flex;
	justify-content: space-between;
	align-items: center;
	height: 50px;
	background-color: rgba(236, 240, 241, 1);
	padding: 16px;
	font-size: 16px;
}

.custom-tree-header .custom-tree-box {
	flex: 1;
	position: unset;
	height: 40px;
	background-color: rgba(236, 240, 241, 1);
	font-size: 12px;
	font-weight: 500;
	align-items: center;
}

:deep(.el-tree-node__expand-icon) {
	display: none;
}

.category-style {
	margin-right: 24px;
}

.category-image {
	width: 78px;
	height: 124px;
	display: flex;
	position: relative;
	border-radius: 4px;
	cursor: pointer;
}

.activeBorder {
	border: 1px solid var(--el-color-primary);
}

.type-img {
	width: 100%;
	height: 100%;
	border-radius: 4px;
}

.category-title {
	font-size: 12px;
	line-height: 14px;
	color: #595959;
	margin-right: 4px;
	margin-top: 8px;
}

.category-icon {
	width: 14px;
	height: 14px;
	margin-top: 8px;
}
</style>
